import sqlite3


class UrlsTableInfo:
    def __init__(self, file: str = None, data: bytes = None):
        if not file and not data:
            raise('need a file or bytes data')

        self.rootpage = 0
        self.type_number = 0
        self.type_names = []

        if file:
            self._get_urls_table_info_db(file)

        if data:
            ...

    def _get_urls_table_info_db(self, file):
        try:
            db = sqlite3.connect(file)
            cursor = db.cursor()
            cursor.execute("SELECT rootpage, sql FROM sqlite_master WHERE type='table' AND name='urls';")
            results = cursor.fetchall()

            if not results or len(results[0]) < 2:
                return

            self.rootpage = results[0][0]
            self.type_number, self.type_names = self._parse_sql(results[0][1])
        finally:
            cursor.close()
            db.close()

    def _parse_sql(self, sql: str):
        res = []

        sql = sql[sql.find('(')+1:]
        type_list = sql.split(',')
        for item in type_list:
            item = item.split(' ')
            if item:
                res.append(item[0])
        return len(res), res


if __name__ == '__main__':
    root = UrlsTableInfo(file='data/History').rootpage()
    print(root)
